package communication.hall
{
	import communication.CertManager;
	import communication.ServerAddress;
	
	import modules.GameDispatcher;
	import modules.login.LoginEvent;
	
	import protobuf.CLIENT_SESSION_CERT;
	import protobuf.LG_PKG_LOGIN_ACK;
	import protobuf.LG_PKG_LOGIN_ACK.ADDR;

	/**
	 * 大厅socket管理
	 * @author xumin.xu
	 */
	public class HallSocketManager
	{
		private static var instance:HallSocketManager;

		public static function init():void
		{
			logger("大厅socket模块初始化");
			if (instance == null)
			{
				instance = new HallSocketManager();
			}
		}

		/**
		 * 初始化大厅socket
		 */
		private function initHallSocket():void
		{
			HallSocket.init();
		}

		/**
		 * 初始化大厅发送者
		 */
		private function initHallMsgSender():void
		{
			logger("初始化大厅发送者");
			HallMsgSender.init();
		}

		/**
		 * 初始化客户端会话公钥
		 * 客户端将接收到的CLIENT_SESSION_CERT结构保存并填上客户端会话公钥。
		 * @param response
		 */
		private function initClientSessionCert(response:LG_PKG_LOGIN_ACK):void
		{
			logger("填上客户端会话公钥");
			
			//收到的CLIENT_SESSION_CERT
			var clientSessionCert:CLIENT_SESSION_CERT = response.clientCert;
			
			var certManager:CertManager = CertManager.getInstance();
			certManager.initClientSessionCert(clientSessionCert);
		}

		private var dispatcher:GameDispatcher = GameDispatcher.instance;

		/** 大厅数据发送者 */
		private function get hallMsgSender():HallMsgSender
		{
			return HallMsgSender.instance;
		}

		public function HallSocketManager()
		{
			addListeners();
		}

		private function addListeners():void
		{
			dispatcher.addEventListener(LoginEvent.LOGIN_SUCCEED, onLoginSucceed);
		}

		/**
		 * 处理登陆成功
		 * @param event
		 */
		private function onLoginSucceed(event:LoginEvent):void
		{
			getHallServerAdderss(event.data);

			initHallMsgSender();
			hallMsgSender.connectHallServer();
		}

		/**
		 * 获取大厅服务器列表
		 * @param data
		 *
		 */
		private function getHallServerAdderss(data:LG_PKG_LOGIN_ACK):void
		{
			var loginAck:LG_PKG_LOGIN_ACK = data;

			logger("获取大厅服务器列表");
			var lobbyservers:Array = [];
			for each (var addr:ADDR in loginAck.addresses)
			{
				var address:ServerAddress = new ServerAddress();
				address.host = addr.host.readUTFBytes(addr.host.length);
				address.port = addr.port;
				address.policy = addr.policyPort;
				lobbyservers.push(address);
			}
			
			GlobalData.lobbyServerArray = lobbyservers;

			initHallSocket();
			
			initClientSessionCert(data);
		}
	}
}
